<template>
  <div class="app-container">
    <div class="search-container">
      <!-- <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属站点" prop="mixingStationCode">
          <el-select v-model="queryParams.mixingStationCode" placeholder="所属站点" clearable>
            <el-option v-for="item in stationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="运单编号" prop="orderCodeFuzzy">
          <el-input v-model="queryParams.orderCodeFuzzy" placeholder="运单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="关联订单" prop="waybillCodeFuzzy">
          <el-input v-model="queryParams.waybillCodeFuzzy" placeholder="关联订单" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNumberFuzzy">
          <el-input v-model="queryParams.carNumberFuzzy" placeholder="车牌号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="搅拌车号" prop="carCodeFuzzy">
          <el-input v-model="queryParams.carCodeFuzzy" placeholder="搅拌车号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerNameFuzzy">
          <el-input v-model="queryParams.customerNameFuzzy" placeholder="客户名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringNameFuzzy">
          <el-input v-model="queryParams.engineeringNameFuzzy" placeholder="工程名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="施工部位" prop="buildPlaceFuzzy">
          <el-input v-model="queryParams.buildPlaceFuzzy" placeholder="施工部位" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="状态" clearable>
            <el-option label="装货中" :value="0" />
            <el-option label="送货中 " :value="1" />
            <el-option label="待卸货(等待中) " :value="2" />
            <el-option label="卸货中 " :value="3" />
            <el-option label="待签收 " :value="4" />
            <el-option label="已签收 " :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常状态" prop="expStatus">
          <el-select v-model="queryParams.expStatus" placeholder="异常状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="异常" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间">
          <el-select v-model="queryParams.timeType">
            <el-option label="开始送货时间" :value="0" />
            <el-option label="送达时间" :value="1" />
            <el-option label="开始卸货时间" :value="2" />
            <el-option label="卸货完成时间 " :value="3" />
            <el-option label="运单签收时间 " :value="4" />
          </el-select>
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" class="ml-8" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form> -->

      <SearchForm
        ref="queryFormRef"
        :model="queryParams"
        :default-collapsed="isCollapsed"
        @search="handleQuery"
        @reset="handleResetQuery"
        @collapsed-change="handleCollapsedChange"
      >
        <el-form-item label="所属站点" prop="mixingStationCode">
          <el-select v-model="queryParams.mixingStationCode" placeholder="所属站点" clearable>
            <el-option v-for="item in stationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="运单编号" prop="orderCodeFuzzy">
          <el-input v-model="queryParams.orderCodeFuzzy" placeholder="运单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="关联订单" prop="waybillCodeFuzzy">
          <el-input v-model="queryParams.waybillCodeFuzzy" placeholder="关联订单" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNumberFuzzy">
          <el-input v-model="queryParams.carNumberFuzzy" placeholder="车牌号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="搅拌车号" prop="carCodeFuzzy">
          <el-input v-model="queryParams.carCodeFuzzy" placeholder="搅拌车号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerNameFuzzy">
          <el-input v-model="queryParams.customerNameFuzzy" placeholder="客户名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringNameFuzzy">
          <el-input v-model="queryParams.engineeringNameFuzzy" placeholder="工程名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="施工部位" prop="buildPlaceFuzzy">
          <el-input v-model="queryParams.buildPlaceFuzzy" placeholder="施工部位" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="状态" clearable>
            <el-option v-for="item in statusList" v-bind="item" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常状态" prop="expStatus">
          <el-select v-model="queryParams.expStatus" placeholder="异常状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="异常" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间">
          <el-select v-model="queryParams.timeType">
            <el-option label="开始送货时间" :value="0" />
            <el-option label="送达时间" :value="1" />
            <el-option label="开始卸货时间" :value="2" />
            <el-option label="卸货完成时间 " :value="3" />
            <el-option label="运单签收时间 " :value="4" />
          </el-select>
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" class="ml-8" />
        </el-form-item>
      </SearchForm>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <div></div>
          <div>
            <el-button type="primary" @click="handleHeaderEdit">
              <template #icon><ep-Setting /></template>
              编辑表头
            </el-button>
            <el-button @click="handleExport">
              <template #icon><ep-Download /></template>
              导出
            </el-button>
          </div>
        </div>
      </template>
      <el-table v-auto-h="isCollapsed" v-loading="loading" :data="tableData" row-key="id" border highlight-current-row>
        <el-table-column v-for="item in tableColumnsData" :key="item.prop" align="center" :label="item.label" v-bind="item">
          <template v-if="checkTemplate(item.prop)" #default="{ row }">
            <template v-if="item.prop === 'orderStatus'">
              <span>{{ statusList.find(item => item.value === row.orderStatus)?.label }}</span>
            </template>
            <template v-else-if="item.prop === 'expStatus'">
              <span v-if="row.expStatus === 1">正常</span>
              <span v-else-if="row.expStatus === 2">异常</span>
            </template>
            <template v-else-if="item.prop === 'expRemark'">
              <span v-if="row.expStatus === 2">{{ row.expRemark }}</span>
            </template>
            <template v-else>
              <el-button type="primary" link size="small" @click="handleDetailClick(row.id)">运单详情</el-button>
              <el-button v-if="row.expStatus === 2" type="primary" class="table-link" link size="small" @click="handleCancelExpClick(row)">
                取消异常
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-model:page="queryParams.nowPage"
        v-model:pagesize="queryParams.pageSize"
        :total="total"
        @pagination="handlePaginationChange"
      />
    </el-card>
    <Detail :id="billId" v-model:visible="detailVisible" />

    <!-- 编辑表头 -->
    <el-drawer v-model="drawerVisible" title="编辑表头" size="30%">
      <el-tree :data="headerData" :allow-drop="allowDrop" draggable node-key="prop" />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleHeaderConfirm">确 定</el-button>
          <el-button @click="handleCloseDrawer">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
/**
 * 运单列表
 */
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { AllowDropType } from 'element-plus/es/components/tree/src/tree.type'
import SearchForm from '@/components/SearchForm/index.vue'

import { useRequest } from '@/hooks/useRequest'
import { getUserTableHeaders, setUserTableHeaders } from '@/api/order/index'
import { getTableData, updateExpStatus, exportTableData } from '@/api/waybill/index'
import type { SearchParams, WaybillData } from '@/api/waybill/index'
import { getMixingStationList, type MixingStationData } from '@/api/customer/customer'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'

import Detail from './detail.vue'

// 订单状态: 0.装货中 1.送货中 2.待卸货(等待中) 3.卸货中 4.待签收 5.已签收
const statusList: OptionType[] = [
  { label: '装货中', value: 0 },
  { label: '送货中', value: 1 },
  { label: '待卸货(等待中)', value: 2 },
  { label: '卸货中', value: 3 },
  { label: '待签收', value: 4 },
  { label: '已签收', value: 5 }
]

const queryFormRef = ref<InstanceType<typeof SearchForm>>(null)

const queryParams = reactive<Partial<SearchParams>>({ timeType: 0, nowPage: 1, pageSize: 10 })

const tableColumnsData = ref([])

const checkTemplate = (prop: string) => {
  return ['operate', 'orderStatus', 'expStatus', 'expRemark'].includes(prop)
}

const route = useRoute()
const routeName = route.name as string
const isCollapsed = ref(true)

getHeadersData()
const { data: stationRes } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queryParams.mixingStationCode = defaultMixingStation.number
    }
  },
  onAfter() {
    handleQuery()
  }
})
const stationOptions = computed(() => stationRes.value?.result || [])

async function getHeadersData() {
  const { result } = await getUserTableHeaders({ routeName })
  if (result.headerCtx) {
    const data = JSON.parse(result.headerCtx)
    tableColumnsData.value = data
  }
}

const drawerVisible = ref(false)
const headerData = shallowRef([])
// 不允许插入
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  return type !== 'inner'
}
const handleHeaderEdit = () => {
  headerData.value = [...tableColumnsData.value]
  drawerVisible.value = true
}
const handleCloseDrawer = () => {
  drawerVisible.value = false
}
const handleHeaderConfirm = () => {
  setUserTableHeaders({
    routeName,
    headerCtx: JSON.stringify(headerData.value)
  }).catch(() => {
    // 失败需要重新刷新
    getHeadersData()
  })
  tableColumnsData.value = [...headerData.value]
  handleCloseDrawer()
}

const total = ref(0)
const tableData = ref([])
const { run, loading } = useRequest(getTableData, {
  manual: true,
  defaultParams: [queryParams],
  onSuccess({ result }) {
    const { records, total: totalRes } = result
    total.value = totalRes
    tableData.value = records
  }
})

const handleCollapsedChange = (collapsed: boolean) => {
  isCollapsed.value = collapsed
}

const handleQuery = () => {
  run(queryParams)
}

const handleExport = () => {
  exportTableData(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.timeType = 0
  queryParams.startTime = ''
  queryParams.endTime = ''
  handleQuery()
}

const handlePaginationChange = (page: number, pageSize: number) => {
  queryParams.nowPage = page
  queryParams.pageSize = pageSize
  handleQuery()
}

const detailVisible = ref(false)
const billId = ref('')
const handleDetailClick = (id: WaybillData['id']) => {
  billId.value = id
  detailVisible.value = true
}

const handleCancelExpClick = (row: WaybillData) => {
  ElMessageBox.confirm('确认取消当前运单的异常状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    // expStatus 异常状态: 1正常 2异常
    // 取消异常状态，变为正常
    await updateExpStatus({ id: row.id, expStatus: 1 })
    handleQuery()
    ElMessage({
      type: 'success',
      message: '取消成功'
    })
  })
}
</script>
<style lang="scss" scoped>
.table-link {
  margin-left: 0;
}
</style>
